const PersonnelList = [
	{ name: "danica", age: 18, sex: "female" },
	{ name: "bob", age: 28, sex: "male" },
	{ name: "bennie", age: 26, sex: "male" },
	{ name: "belen", age: 32, sex: "female" },
	{ name: "astrid", age: 28, sex: "female" },
	{ name: "xzavier", age: 24, sex: "male" },
	{ name: "cornelia", age: 24, sex: "female" },
	{ name: "esther", age: 26, sex: "male" },
	{ name: "esther", age: 28, sex: "female" },
	{ name: "regina", age: 18, sex: "female" },
	{ name: "lilian", age: 18, sex: "male" },
];

/* 
分组处理 用reduce 方法实现
*/

// const res = PersonnelList.reduce((acc, cur) => {
//     if (!acc[cur.age]) {
//         acc[cur.age] = { count: 0, userlist: [] };
//     }
//     acc[cur.age].count++;
//     acc[cur.age].userlist.push(cur)
//     return acc;
// }, {});
// console.log(res);
// console.log(Object.values(res).map(item => item.userlist));


// const res = PersonnelList.reduce((acc, cur) => {
//     if (!acc[cur.age]) {
//         acc[cur.age] =  [] ;
//     }
//     acc[cur.age].push(cur)
//     return acc;
// }, {});

// console.log(res);



// 根据动态条件进行分组
const group = ( array , condition = "age") => {
    const res = array.reduce((acc, cur) => {
        let key = cur[condition] // 封装的关键在于 如何获取这个键名  而不是一个属性名  应当封装成一个函数
        if (!acc[key]) {
            acc[key] =  [] ;
        }
        acc[key].push(cur)
        return acc;
    }, {});
    return res
}
// console.log(group(PersonnelList , 'sex'));
// console.log(group(PersonnelList , "name" ));


// 再次封装
const groupBy = ( array , generateKey) => {
    const res = array.reduce((acc, cur) => {
        let key = generateKey(cur)
        console.log(key);
        
        if (!acc[key]) {
            acc[key] =  [] ;
        }
        acc[key].push(cur)
        return acc;
    }, {});
    return res
}

console.log(groupBy(PersonnelList , (item) => item.sex)); // 按性别分组
console.log(groupBy(PersonnelList , (item) => item.age)); // 按照年龄分组
console.log(groupBy(PersonnelList , (item) => `${item.age}-${item.sex}`)); // 按照年龄-性别分组


